package user;

import java.io.*;

public class  UserDaoIO implements UserDao{
    @Override
    public void register(User user) throws IOException {
        BufferedWriter bw=null;
        try {
            //创建字符缓冲留对象

          bw = new BufferedWriter(new FileWriter("d:\\user.txt",true));
          //将user对象中的各属性以--为分别分隔符作为一行文本写入文件
       bw.write(user.getId()+"--"+user.getName()+"--"
               +user.getAge()+"--"+user.getPassword());
       //加入行分隔符
       bw.newLine();
       //刷新
       bw.flush();
        }catch (IOException e){
            System.out.println("出现异常"+e.getMessage());
        }finally {
            if(bw!=null){
                try{
                    bw.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean login(String name, String password) {
      /*
      1读取文件中每一行数据
      创建字符缓冲刘对象
      循环操作
      调用该对象的readLine()方法读取一行数据
      2将相关的数据传入的name和password
      若相同返回true
      3最后返回flase
       */
        BufferedReader br=null;
        try{
            br=new BufferedReader(new FileReader("d\\user.txt"));
       String line=null;
           while((line=br.readLine())!=null){
           //读取到一行记录line
           //将line以--风格得到string数组;
           String[]data=line.split("--");
           //取出数组中的地2.3个元素传入的name和password比较
           if(data[1].equals(name)&&data[2].equals(password)){
               return true;
           }
       }
        } catch (Exception e) {
            System.out.println("出现异常"+e.getMessage());
        }
        finally {
            if(br!=null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public void querAll() {
BufferedReader br=null;
try {
    br=new BufferedReader(new FileReader("d\\user.txt"));
       String line=null;
    while((line=br.readLine())!=null){
        System.out.println(line);
    }
} catch (Exception e) {
    System.out.println("出现异常"+e.getMessage());
}finally {
    if (br!=null){
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    }
}
